package com.hospicpc.demos.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;


public class DownloadImgUtils {

    private final RestTemplate restTemplate;

    public DownloadImgUtils(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }


    public void downloadImage(String imageUrl, String destinationPath) throws IOException {
        ResponseEntity<byte[]> responseEntity = restTemplate.exchange(
                imageUrl,
                HttpMethod.GET,
                null,
                byte[].class
        );

        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            byte[] imageData = responseEntity.getBody();
            // File dest = new File(destinationPath);
            // try (FileOutputStream fos = new FileOutputStream(dest)) {
            //     fos.write(imageData);
            //     fos.flush();
            //     System.out.println("Image downloaded successfully: " + dest.getAbsolutePath());
            // }
            System.out.println("Image downloaded successfully: ");
        } else {
            System.out.println("Error downloading image: " + responseEntity.getStatusCode());
        }
    }

    // 如果需要处理URLResource，例如将图片作为Spring Resource返回，可以添加以下方法
    public Resource getImageAsResource(String imageUrl) throws MalformedURLException {
        return new UrlResource(imageUrl);
    }
}